package priorityqueue;

import java.util.Comparator;
import java.util.PriorityQueue;

class Student implements Comparable<Student>{
    public int id;
    public String name;

    public int score;

    public Student(int score, int id, String name) {
        this.score = score;
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Student o){
        //认为this < o,就返回<0的整数
        //认为this > o,就返回>0的整数
        //认为this = o,就返回=0的整数

        //小堆写法
//        return this.score - o.score;
        //大堆写法
        return o.score - this.score;
    }
}

//可以写出多个比较器,后面想用哪个比较器,直接创建比较器的实例来传即可
class StudentComparator1 implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o2.score - o1.score;
    }
}

class StudentComparator2 implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.id - o2.id;
    }
}

class StudentComparator3 implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o2.name.compareTo(o1.name);
    }
}
public class Test3 {

    public static void main(String[] args) {
        //使用优先级队列,保存自定义类型
//        PriorityQueue<Student> queue = new PriorityQueue<>(new Comparator<Student>() {
//            @Override
//            public int compare(Student o1, Student o2) {
//                return o2.score - o1.score;
//            }
//        });

          PriorityQueue<Student> queue = new PriorityQueue<>(new StudentComparator2());

        //如果没有定义优先级比较规则而直接执行程序,程序在运行时就会出现异常
        //对于优先级队列来说,如果指定了Comparator,就按照Comparator的规则来比较
        //如果没有指定Comparator,就尝试把元素使用 Comparable接口 来实现
        queue.offer(new Student(99,1,"Bin"));
        queue.offer(new Student(55,2,"Bob"));
        queue.offer(new Student(88,5,"Amy"));
        queue.offer(new Student(0,9,"David"));

        while(!queue.isEmpty()){
            System.out.println(queue.poll());
        }


    }

    //使用Comparable和Comparator的情况

    //使用Comparable的前提:
    //1,要比较的类是自己写的,随时可以修改
    //2,针对这个类的比较规则是唯一的

    //使用Comparator
    //1,不要求类是自己写的
    //2,针对同一个类型,可以创建多个

    //Comparator的比较范围更广,但是比较的标准不唯一
}
